package georah.map.tools
{
    import flash.display.Shape;
    import flash.geom.Point;

    import georah.map.MapMouseEvent;

    public final class DragZoom extends Navigation
    {
        override public final function get keyboardLocked():Boolean
        {
            return false;
        }

        override public final function get mouseLocked():Boolean
        {
            return true;
        }

        private var _rect:Shape = new Shape();

        override protected final function this_disableHandler(event:MapToolEvent):void
        {
            map.acetate.removeChild(_rect);

            map.removeEventListener(MapMouseEvent.DRAG_START, map_dragStartHandler);
            map.removeEventListener(MapMouseEvent.DRAG_PROGRESS, map_dragProgressHandler);
            map.removeEventListener(MapMouseEvent.DRAG_STOP, map_dragStopHandler);

            super.this_disableHandler(event);
        }

        override protected final function this_enableHandler(event:MapToolEvent):void
        {
            super.this_enableHandler(event);

            map.addEventListener(MapMouseEvent.DRAG_START, map_dragStartHandler);
            map.addEventListener(MapMouseEvent.DRAG_PROGRESS, map_dragProgressHandler);
            map.addEventListener(MapMouseEvent.DRAG_STOP, map_dragStopHandler);

            map.acetate.addChild(_rect);
        }

        private var _dragZoomFrom:Point = null;

        private final function map_dragStartHandler(event:MapMouseEvent):void
        {
            _dragZoomFrom = event.pixel;
            dragZoomStart(event.where);
        }

        private final function map_dragProgressHandler(event:MapMouseEvent):void
        {
            _rect.graphics.clear();
            _rect.graphics.lineStyle(2, 0x000000, 0.5);
            _rect.graphics.beginFill(0xffffff, 0.5);
            var rectx:Number = Math.min(_dragZoomFrom.x, event.pixel.x) - map.layers.x;
            var recty:Number = Math.min(_dragZoomFrom.y, event.pixel.y) - map.layers.y;
            var rectw:Number = Math.abs(event.pixel.x - _dragZoomFrom.x);
            var recth:Number = Math.abs(event.pixel.y - _dragZoomFrom.y);
            _rect.graphics.drawRect(rectx, recty, rectw, recth);
            _rect.graphics.endFill();
        }

        private final function map_dragStopHandler(event:MapMouseEvent):void
        {
            _rect.graphics.clear();
            _dragZoomFrom = null;
            if (event.rawMouseEvent.altKey as Boolean)
            {
                dragZoomStop(event.where, Navigation.ZOOM_OUT);
            }
            else
            {
                dragZoomStop(event.where, Navigation.ZOOM_IN);
            }
        }

    }
}